import json
import redis

from PySide6.QtCore import QThread, Signal


# 用Pysdie6的QThread实现redis订阅数据的去读
class RedisSubscribe(QThread):
    signal = Signal(dict)

    def __init__(self):
        super().__init__()
        self.is_running = True  # 新增退出标志
        if not self.get_redis_config():
            raise ValueError('Redis配置参数获取失败')
        redis_conn = redis.Redis(**self.get_redis_config())
        redis_conn.ping()  # 显式测试连接
        self.pubsub = redis_conn.pubsub()
        self.pubsub.subscribe('operation_channel')

    @staticmethod
    def get_redis_config():
        """获取redis配置参数"""
        with open('config\\package.json', 'r', encoding='utf-8') as reader:
            config = json.loads(reader.read())
            redis_config = config.get('redis_config', {})
            return redis_config

    def run(self):
        while self.is_running:  # 使用标志控制循环
            message = self.pubsub.get_message()  # 主动获取消息而非阻塞监听
            if message:
                data = message.get('data', b'')
                if data and data != 1:
                    self.signal.emit(json.loads(data.decode('utf-8')))
            self.msleep(100)  # 短暂休眠降低CPU占用
